﻿using log4net;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WindowsInput;
using WindowsInput.Native;

namespace WpfApp4
{

    public delegate void SendLogDelegate();

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static ILog log = LogManager.GetLogger(typeof(MainWindow));

        private String loginUrl = ConfigurationManager.AppSettings["loginUrl"];
        private String userName = ConfigurationManager.AppSettings["userName"];
        private String passWord = ConfigurationManager.AppSettings["passWord"];

        private String homeUrl = ConfigurationManager.AppSettings["homeUrl"];

        private String Authorization;

        private Suspension suspension = null;
        private MultipleWindow multipleWindow = null;

        public MainWindow()
        {
            InitializeComponent();

            #region 启动时串口最大化显示
            Rect rc = SystemParameters.WorkArea; //获取工作区大小
            this.Left = 0; //设置位置
            this.Top = 0;
            this.Width = rc.Width;
            this.Height = rc.Height;
            #endregion
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            log.Info("Window_Loaded.");
            await webView1.EnsureCoreWebView2Async();
            webView1.NavigationCompleted += WebView1_login;

            await beLogin();

            // 写入cookie


        }

        public void tike() {
            log.Info("Tike");

            if (this.Visibility == Visibility.Visible)
            {
                log.Info("Main Hide.");
                this.Visibility = Visibility.Hidden;
                multipleWindow.Visibility = Visibility.Visible;
            }
            else {
                log.Info("Main Show.");
                this.Visibility = Visibility.Visible;
                multipleWindow.Visibility = Visibility.Hidden;
            }

        }

        private async void WebView1_login(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            webView1.NavigationCompleted -= WebView1_login;

           await webView1.CoreWebView2.ExecuteScriptAsync("localStorage.setItem(\"accout-token\",\"" + Authorization + "\")");
           await webView1.CoreWebView2.ExecuteScriptAsync("localStorage.setItem(\"user_account\",\"" + userName + "\")");

            webView1.Source = new Uri(homeUrl);

            suspension = new Suspension();
            suspension.sendLogDelegate = tike;
            suspension.Show();

            multipleWindow = new MultipleWindow();
            multipleWindow.Show();
            multipleWindow.Visibility = Visibility.Hidden;
        }

        private async Task<int> beLogin()
        {
            log.Info("beLogin start.");
            var client = new HttpClient();

            try
            {


                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Post,
                    RequestUri = new Uri(loginUrl),
                    Content = new StringContent("{\"username\":\""+ userName + "\",\"password\":\""+  passWord  + "\"}")
                    {
                        Headers =        {
            ContentType = new MediaTypeHeaderValue("application/json")
        }
                    }
                };
                using (var response = await client.SendAsync(request))
                {
                    response.EnsureSuccessStatusCode();
                    var body = await response.Content.ReadAsStringAsync();

                    var json = JsonConvert.DeserializeObject<TokenJson>(body);

                    Authorization = json.Token;
                    saveToken(json.Token);
                    log.Info(Authorization);
                }
                request.Dispose();
            }
            catch (Exception ex)
            {
                log.Error("beLogin Exception：", ex);
            }
            finally
            {
                client.Dispose();
            }

            log.Info("beLogin end.");
            return 0;
        }


        private void saveToken(string token) {
            Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);

            try
            {
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = configFile.AppSettings.Settings;
                if (settings["token"] == null)
                {
                    settings.Add("token", token);
                }
                else
                {
                    settings["token"].Value = token;
                }
                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
            }
            catch (ConfigurationErrorsException)
            {
                log.Error("AppSettings更新出现异常");
            }


        }

        private void Window_Closed(object sender, EventArgs e)
        {
            System.Windows.Application.Current.Shutdown();
        }
    }


    partial class TokenJson
    {
        String token;

        public string Token { get => token; set => token = value; }
    }
}
